import {
  transformExtent,
  fromLonLat,
  transform,
  get as getProjection,
  Projection,
} from "ol/proj";
import VectorSource from "ol/source/Vector";
import TileLayer from "ol/layer/Tile";
import WMTS from "ol/source/WMTS.js";
import WMTSTileGrid from "ol/tilegrid/WMTS.js";
import TileWMS from "ol/source/TileWMS";
import ImageWMS from "ol/source/ImageWMS";
import { XYZ as XYZSource } from "ol/source";
import { Style, Fill, Stroke, Circle, Icon, Text } from "ol/style";
import VectorLayer from "ol/layer/Vector";
import GeoJSON from "ol/format/GeoJSON";
import Feature from "ol/Feature";
import KML from "ol/format/KML";
import { Point, LineString } from "ol/geom";
import { Group } from "ol/layer";
import ImageLayer from "ol/layer/Image";
import TileGrid from "ol/tilegrid/TileGrid";
import Overlay from "ol/Overlay";
import {
  TDKEY,
  GEOSERVERURL,
  EV_SERVER,
  AIS_GEOSERVERURL,
} from "@/config/mapConfig.js";
import { WindLayer } from "ol-wind";
import { getWindDataByJson } from "../api";
import wurenji from "@/assets/image/wurenji.png";
import { unByKey } from "ol/Observable";
import { useConfigStore } from "../store/useConfigStore";
import { storeToRefs } from "pinia";
import startImg from "@/assets/image/start.png";
import endImg from "@/assets/image/end.png";
import arrowImg from "@/assets/image/arrow.png";
import ship from "@/assets/image/ship.png";
const userConfigStore = useConfigStore();
const { envPopperInfo } = storeToRefs(userConfigStore);

let clickEventList = [];
let popupList = [];

let aisVectorSource = null;
let aisTimer = null;
/**
 * 根据四至定位
 * @param {*} map 地图
 * @param {*} extent 四至
 */
export function zoomToExtent(map, extent) {
  const [minX, minY, maxX, maxY] = [0, 0, 1068, 653];
  const padding = [minY + 16, 1068 - maxX, 717 - maxY + 16, minX];
  map.getView().fit(extent, {
    padding,
    duration: 1000,
  });
}
// 根据点定位
export function fitCenter(map, point) {
  map.getView().animate({
    // 只设置需要的属性即可
    center: point, // 中心点
    zoom: 12, // 缩放级别
    rotation: undefined, // 缩放完成view视图旋转弧度
    duration: 1000, // 缩放持续时间，默认不需要设置
  });
}
/**
 * 添加风场
 * @param {*} map 地图
 * @param {*} ncdata 风场数据
 */
// 添加风流粒子
export function addWindyLayer(map, ncdata) {
  const windLayer = new WindLayer(ncdata, {
    foceRender: false,
    windOptions: {
      globalAlpha: 0.9, // 粒子透明度
      // maxAge: 10, // 存活最大帧数
      velocityScale: 1 / 10000, // 粒子速度
      // paths: 5000, // 粒子数量
      lineWidth: 4,
      frameRate: 45,
      colorScale: () => {
        return "#ff473c";
      },
      width: 3,
    },
  });
  map.addLayer(windLayer);
}

/**
 * 加载geoserver WMS服务
 * @param {*} workspace 工作空间
 * @param {*} layerName 图层名称
 * @param {*} style 样式
 * @param {*} tilesOrigin 四至范围
 * @returns tileLayers
 */
export function addWMSTiles(openMap, layerName, id) {
  let layer = new TileLayer({
    name: "环境监测",
    source: new TileWMS({
      url: `${GEOSERVERURL}geoserver/js/wms?`,
      params: {
        VERSION: "1.1.1",
        tiled: true,
        LAYERS: layerName,
        SRS: "EPSG:4326",
        exceptions: "application/vnd.ogc.se_inimage",
      },
    }),
    id,
  });
  openMap.addLayer(layer);
}

// 移除定时刷新
export function removeAisTimer() {
  if (aisTimer) {
    clearInterval(aisTimer);
    aisTimer = null;
  }
}
//添加AIS数据
export function addWMSTiles_AIS(openMap, layerName, id) {
  aisVectorSource = new TileWMS({
    url: `${AIS_GEOSERVERURL}wms?`,
    params: {
      VERSION: "1.1.1",
      tiled: true,
      LAYERS: layerName,
      exceptions: "application/vnd.ogc.se_inimage",
    },
  });
  let layer = new TileLayer({
    source: aisVectorSource,
    id,
  });
  openMap.addLayer(layer);
  // 4. 设置3秒定时刷新
  aisTimer = setInterval(() => {
    aisVectorSource.updateParams({
      TIME: new Date().toISOString(),
    }); // 强制刷新瓦片
  }, 2000); // 3000毫秒 = 3秒
  return layer;
}
/**
 * 加载WMS服务---ImageLayer方式
 * @param {*} openMap
 * @param {*} layerName
 * @param {*} id
 * @param {*} zIndex
 */
export function addImgWMS(openMap, layerName, id, zIndex) {
  let layer = new ImageLayer({
    source: new ImageWMS({
      ratio: 1,
      url: `${EV_SERVER}earthview/rest/services/vectorserver/wms?`,
      // url: `${GEOSERVERURL}wms?`,
      params: {
        FORMAT: "image/png",
        VERSION: "1.1.1",
        STYLES: layerName,
        LAYERS: layerName,
        exceptions: "application/vnd.ogc.se_inimage",
      },
    }),
    id,
    name: layerName,
    maxZoom: layerName == "渔区网格线" ? 12 : 18,
  });
  if (zIndex) {
    layer.setZIndex(zIndex);
  }
  openMap.addLayer(layer);
}
/**
 * 加载geoserver WMTS服务
 * @param {*} layer 图层名称
 * @param {*} style 样式
 * @returnstileLayers
 */
export function addWMTSTiles(openMap, layer, id, style) {
  const gridNames = [
    "EPSG:4326:0",
    "EPSG:4326:1",
    "EPSG:4326:2",
    "EPSG:4326:3",
    "EPSG:4326:4",
    "EPSG:4326:5",
    "EPSG:4326:6",
    "EPSG:4326:7",
    "EPSG:4326:8",
    "EPSG:4326:9",
    "EPSG:4326:10",
    "EPSG:4326:11",
    "EPSG:4326:12",
    "EPSG:4326:13",
    "EPSG:4326:14",
    "EPSG:4326:15",
    "EPSG:4326:16",
    "EPSG:4326:17",
    "EPSG:4326:18",
    "EPSG:4326:19",
    "EPSG:4326:20",
    "EPSG:4326:21",
  ];
  //切片大小
  const resolutions = [
    0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625,
    0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625,
    6.866455078125e-4, 3.4332275390625e-4, 1.71661376953125e-4,
    8.58306884765625e-5, 4.291534423828125e-5, 2.1457672119140625e-5,
    1.0728836059570312e-5, 5.364418029785156e-6, 2.682209014892578e-6,
    1.341104507446289e-6, 6.705522537231445e-7, 3.3527612686157227e-7,
  ];
  //设置地图投影
  const projection = new Projection({
    code: "EPSG:4326", //投影编码
    units: "degrees",
    axisOrientation: "neu",
  });
  const wmtsLayer = new TileLayer({
    source: new WMTS({
      url: `${GEOSERVERURL}gwc/service/wmts?`,
      layer: layer,
      style,
      matrixSet: "EPSG:4326",
      format: "image/png",
      projection: projection,
      //切片信息
      tileGrid: new WMTSTileGrid({
        tileSize: [256, 256],
        extent: [-180.0, -90.0, 180.0, 90.0], //范围
        origin: [-180.0, 90.0],
        resolutions: resolutions,
        matrixIds: gridNames,
      }),
      //
      wrapX: false,
      crossOrigin: "anonymous",
    }),
    id,
  });
  openMap.addLayer(wmtsLayer);
}

/**
 * 加载EVserver shp WMTS服务
 * @param {*} workspace 工作空间
 * @param {*} layerName 图层名称
 * @param {*} style 样式
 * @param {*} tilesOrigin 四至范围
 *
 */
export function addShpEVWMTSTiles(openMap, layer, id) {
  const gridNames = [
    "EPSG:4326:0",
    "EPSG:4326:1",
    "EPSG:4326:2",
    "EPSG:4326:3",
    "EPSG:4326:4",
    "EPSG:4326:5",
    "EPSG:4326:6",
    "EPSG:4326:7",
    "EPSG:4326:8",
    "EPSG:4326:9",
    "EPSG:4326:10",
    "EPSG:4326:11",
    "EPSG:4326:12",
    "EPSG:4326:13",
    "EPSG:4326:14",
    "EPSG:4326:15",
    "EPSG:4326:16",
    "EPSG:4326:17",
    "EPSG:4326:18",
    "EPSG:4326:19",
    "EPSG:4326:20",
    "EPSG:4326:21",
  ];
  //切片大小
  const resolutions = [
    0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625,
    0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625,
    6.866455078125e-4, 3.4332275390625e-4, 1.71661376953125e-4,
    8.58306884765625e-5, 4.291534423828125e-5, 2.1457672119140625e-5,
    1.0728836059570312e-5, 5.364418029785156e-6, 2.682209014892578e-6,
    1.341104507446289e-6, 6.705522537231445e-7, 3.3527612686157227e-7,
  ];
  let tileLayer = new TileLayer({
    id,
    source: new WMTS({
      tileLoadFunction: (tile, src) => {
        src.replace("layer=", "layer=");
        src.replace("style=", "style=");
        src.replace("tilematrixset=", "tileMatrixset=");
        src.replace("Service=", "service=");
        src.replace("Request=", "request=");
        src.replace("Version=", "version=");
        src.replace("Format=", "FORMAT=");
        src.replace("TileMatrix=", "tileMatrix=");
        src.replace("TileCol=", "tileCol=");
        src.replace("TileRow=", "tileRow=");
        tile.getImage().src = src;
      },
      url: `${EV_SERVER}earthview/rest/services/vectorserver/wmts?serviceName=${layer}`,
      layer: layer,
      matrixSet: "EPSG:4326",
      format: "image/png",
      buffer: 1,
      isBaseLayer: true,
      style: "shp_big",
      tileGrid: new WMTSTileGrid({
        tileSize: [256, 256],
        extent: [-180.0, -90.0, 180.0, 90.0], //范围
        origin: [-180.0, 90.0],
        resolutions: resolutions,
        matrixIds: gridNames,
      }),
    }),
    zIndex: 100,
  });
  openMap.addLayer(tileLayer);
}

/**
 * 加载EVserver WMTS服务  ETM
 * @param {*} workspace 工作空间
 * @param {*} layerName 图层名称
 * @param {*} style 样式
 * @param {*} tilesOrigin 四至范围
 *
 */
export function addEVWMTSByETMTiles(openMap, layer, id) {
  // const gridNames = [
  //   "EPSG:4326:-2",
  //   "EPSG:4326:-1",
  //   "EPSG:4326:0",
  //   "EPSG:4326:1",
  //   "EPSG:4326:2",
  //   "EPSG:4326:3",
  //   "EPSG:4326:4",
  //   "EPSG:4326:5",
  //   "EPSG:4326:6",
  //   "EPSG:4326:7",
  //   "EPSG:4326:8",
  //   "EPSG:4326:11",
  //   "EPSG:4326:12",
  //   "EPSG:4326:13",
  //   "EPSG:4326:14",
  //   "EPSG:4326:15",
  //   "EPSG:4326:16",
  //   "EPSG:4326:17",
  //   "EPSG:4326:18",
  //   "EPSG:4326:19",
  //   "EPSG:4326:20",
  //   "EPSG:4326:21",
  // ];
  // //切片大小
  // const resolutions = [
  //   0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625,
  //   0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625,
  //   6.866455078125e-4, 3.4332275390625e-4, 1.71661376953125e-4,
  //   8.58306884765625e-5, 4.291534423828125e-5, 2.1457672119140625e-5,
  //   1.0728836059570312e-5, 5.364418029785156e-6, 2.682209014892578e-6,
  //   1.341104507446289e-6, 6.705522537231445e-7, 3.3527612686157227e-7,
  // ];
  // let tileLayer = new TileLayer({
  //   id,
  //   source: new WMTS({
  //     tileLoadFunction: (tile, src) => {
  //       src.replace("layer=", "layer=");
  //       src.replace("style=", "style=");
  //       src.replace("tilematrixset=", "tileMatrixset=");
  //       src.replace("Service=", "service=");
  //       src.replace("Request=", "request=");
  //       src.replace("Version=", "version=");
  //       src.replace("Format=", "FORMAT=");
  //       src.replace("TileMatrix=", "tileMatrix=");
  //       src.replace("TileCol=", "tileCol=");
  //       src.replace("TileRow=", "tileRow=");
  //       tile.getImage().src = src;
  //     },
  //     url: `${EV_SERVER}earthview/rest/services/tileserver/wmts?serviceName=${layer}`,
  //     layer: layer,
  //     matrixSet: "EPSG:4326",
  //     format: "image/png",
  //     buffer: 1,
  //     isBaseLayer: true,
  //     style: "default",
  //     tileGrid: new WMTSTileGrid({
  //       tileSize: [256, 256],
  //       extent: [-180.0, -90.0, 180.0, 90.0], //范围
  //       origin: [-180.0, 90.0],
  //       resolutions: resolutions,
  //       matrixIds: gridNames,
  //     }),
  //   }),
  //   zIndex: layer.indexOf("NDVI") !== -1 ? 1 : 2,
  // });
  const tileSize = 512;
  const resolutions = [];
  const span = 180 / tileSize / 5;
  for (let i = 0; i <= 19; i++) {
    resolutions.push(span / Math.pow(2, i));
  }
  const source = new XYZSource({
    tileGrid: new TileGrid({
      origin: [-180, -90],
      resolutions: resolutions,
      tileSize: tileSize,
    }),
    projection: "EPSG:4326",
    tileUrlFunction: (bounds) => {
      const z = bounds[0] - 4;
      const x = bounds[1];
      const y = -bounds[2] - 1;
      return (
        `${EV_SERVER}earthview/rest/services/tileserver/wmts?serviceName=${layer}&service=wmts&request=GetTile&version=1.0.0&style=default&layer=${layer}&` +
        `tileMatrix=${z}&tileRow=${y}&tileCol=${x}&FORMAT=image/png&tileMatrixset=EPSG:4326`
      );
    },
    wrapX: false,
  });
  const tileLayer = new TileLayer({
    id,
    zIndex: layer.indexOf("NDVI") !== -1 ? 1 : 2,
    source: source,
  });
  openMap.addLayer(tileLayer);
}
/**
 * 加载EVserver WMS服务
 * @param {*} workspace 工作空间
 * @param {*} layerName 图层名称
 * @param {*} style 样式
 * @param {*} tilesOrigin 四至范围
 *
 */
export function addEVWMTSTiles(openMap, layer, id) {
  let flag = false;
  singleBandLayer.forEach((filterLayer) => {
    if (layer.includes(filterLayer)) {
      flag = true;
    }
  });
  const gridNames = [
    "EPSG:4326:0",
    "EPSG:4326:1",
    "EPSG:4326:2",
    "EPSG:4326:3",
    "EPSG:4326:4",
    "EPSG:4326:5",
    "EPSG:4326:6",
    "EPSG:4326:7",
    "EPSG:4326:8",
    "EPSG:4326:9",
    "EPSG:4326:10",
    "EPSG:4326:11",
    "EPSG:4326:12",
    "EPSG:4326:13",
    "EPSG:4326:14",
    "EPSG:4326:15",
    "EPSG:4326:16",
    "EPSG:4326:17",
    "EPSG:4326:18",
    "EPSG:4326:19",
    "EPSG:4326:20",
    "EPSG:4326:21",
  ];
  //切片大小
  const resolutions = [
    0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625,
    0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625,
    6.866455078125e-4, 3.4332275390625e-4, 1.71661376953125e-4,
    8.58306884765625e-5, 4.291534423828125e-5, 2.1457672119140625e-5,
    1.0728836059570312e-5, 5.364418029785156e-6, 2.682209014892578e-6,
    1.341104507446289e-6, 6.705522537231445e-7, 3.3527612686157227e-7,
  ];
  let tileLayer = new TileLayer({
    id,
    source: new WMTS({
      tileLoadFunction: (tile, src) => {
        src.replace("layer=", "layer=");
        src.replace("style=", "style=");
        src.replace("tilematrixset=", "tileMatrixset=");
        src.replace("Service=", "service=");
        src.replace("Request=", "request=");
        src.replace("Version=", "version=");
        src.replace("Format=", "FORMAT=");
        src.replace("TileMatrix=", "tileMatrix=");
        src.replace("TileCol=", "tileCol=");
        src.replace("TileRow=", "tileRow=");
        tile.getImage().src = src;
      },
      url: `${EV_SERVER}earthview/rest/services/rasterserver/wmts?serviceName=${layer}`,
      layer: layer,
      matrixSet: "EPSG:4326",
      format: "image/png",
      buffer: 1,
      isBaseLayer: true,
      style: flag ? "insarOcean" : "", //单波段影像配置样式
      tileGrid: new WMTSTileGrid({
        tileSize: [256, 256],
        extent: [-180.0, -90.0, 180.0, 90.0], //范围
        origin: [-180.0, 90.0],
        resolutions: resolutions,
        matrixIds: gridNames,
      }),
    }),
    zIndex: layer.indexOf("NDVI") !== -1 ? 1 : 2,
  });
  openMap.addLayer(tileLayer);
}
// 加载在线shp数据
// export function addShp(openMap, url, id) {
//   console.log(url);
//   // 解析shp
//   // 定义geojson数组, 一个shp里会有多个面, 即有多个geometry
//   let layerArr = [];
//   shapefile
//     .open(url)
//     .then((source) => {
//       source.read().then(function log(result) {
//         // 所有数据解析完
//         if (result.done) {
//           let layerGroup = new Group({
//             layers: layerArr,
//             id,
//           });
//           openMap.addLayer(layerGroup);
//           fitLayer(layerGroup, openMap);
//           return;
//         }
//         let polygon = null;
//         if (result.value.geometry.type == "Point") {
//           // 每次解析时的操作
//           polygon = new Feature({
//             geometry: new Point(result.value.geometry.coordinates),
//           });
//         }
//         if (result.value.geometry.type == "Polygon") {
//           // 每次解析时的操作
//           polygon = new Feature({
//             geometry: new Polygon(result.value.geometry.coordinates),
//           });
//         }
//         if (result.value.geometry.type == "LineString") {
//           // 每次解析时的操作
//           polygon = new Feature({
//             geometry: new LineString(result.value.geometry.coordinates),
//           });
//         }
//         //设置区样式信息
//         polygon.setStyle(
//           new Style({
//             //填充色
//             fill: new Fill({
//               color: getColorStr("30"),
//             }),
//             //边线颜色
//             stroke: new Stroke({
//               // color: getColorStr("ff"),
//               color: "#8bc34a",
//               width: 2,
//             }),
//             //形状
//             image: new Circle({
//               radius: 7,
//               fill: new Fill({
//                 color: "#8bc34a",
//               }),
//             }),
//           })
//         );
//         let uploadSource = new VectorSource({
//           features: [polygon],
//         });
//         let uploadLayer = new VectorLayer({
//           renderMode: "vector",
//           source: uploadSource,
//         });
//         uploadLayer.setZIndex(1);
//         layerArr.push(uploadLayer);
//         return source.read().then(log);
//       });
//     })
//     .catch((error) => {
//       this.$message.error("读取shp文件失败");
//     });
// }
//加载解译矢量中在线shp数据
export function addShp(openMap, url, id, color) {
  let featuresArr = [];
  let style = new Style({
    //填充色
    fill: new Fill({
      // color: getColorStr("30"),
      color: "#B8B2B24D",
    }),
    //边线颜色
    stroke: new Stroke({
      // color: "#8bc34a",
      // color: "#7ED321",
      color: color,
      width: 2,
    }),
    //形状
    image: new Circle({
      radius: 7,
      fill: new Fill({
        // color: "#8bc34a",
        // color: "#7ED321",
        color: color,
      }),
    }),
  });
  shapefile
    .open(url)
    .then((source) =>
      source.read().then(function log(result) {
        if (result.done) return;
        featuresArr.push(result.value);
        return source.read().then(log);
      })
    )
    .then(() => {
      const features2Geo = {
        type: "FeatureCollection",
        name: id,
        crs: {
          type: "name",
          properties: { name: "urn:ogc:def:crs:OGC:1.3:CRS84" },
        },
        features: featuresArr,
      };
      let features = new GeoJSON().readFeatures(features2Geo);
      const vectorlayer = new VectorLayer({
        source: new VectorSource(),
        renderMode: "vector",
        zIndex: 2000000,
        style,
        id,
      });
      vectorlayer.getSource().addFeatures(features);
      openMap.addLayer(vectorlayer);
      // // 静态资源图层定位
      // let extent = vectorlayer.getSource().getExtent();
      // //定位范围
      // openMap.getView().fit(extent, {
      //   duration: 1000, //动画的持续时间,
      // });
    })
    .catch((error) => console.error(error.stack));
}
// 加载在线kml数据
export function addKml(openMap, url, id) {
  // 加载KML文件
  fetch(url)
    .then((response) => response.text())
    .then((kml) => {
      // 解析KML文件
      const features = new KML({
        extractStyles: false,
      }).readFeatures(kml);
      // 创建一个图层并将解析的特征添加到它
      const vectorLayer = new VectorLayer({
        id,
        zIndex: 10005,
        source: new VectorSource({
          features: features,
        }),
        style: function (feature) {
          // 使用解析出的样式或者自定义样式
          const style = feature.getStyle();
          if (style) {
            return style;
          }
          // 如果没有样式，则返回默认样式
          return [
            new Style({
              text: new Text({
                font: "normal 15px 黑体",
                // // 对其方式
                textAlign: "left",
                // 基准线
                textBaseline: "middle",
                offsetY: 0,
                offsetX: 15,
                backgroundFill: new Stroke({
                  color: "#2196F3",
                }),
                // 文本填充样式
                fill: new Fill({
                  color: "rgba(236,218,20,1)",
                }),
                padding: [5, 5, 5, 5],
                text: feature.values_.name,
              }),
              stroke: new Stroke({
                color: "#1778dc",
                width: 3,
              }),
              image: new Icon({
                anchor: [0.5, 36],
                anchorOrigin: "top-right",
                anchorXUnits: "fraction",
                anchorYUnits: "pixels",
                src: require("../assets/images/icon/临时起降点.png"), // 替换为实际图标路径
              }),
            }),
          ];
        },
      });
      // 将图层添加到地图
      openMap.addLayer(vectorLayer);
    });
  // let vetorLayer = new VectorLayer({
  //   source: new VectorSource({
  //     url,
  //     format: new KML({
  //       extractStyles: false,
  //     }),
  //   }),
  //   style: new Style({
  //     fill: new Fill({
  //       color: [0xff, 0xff, 0x33, 0.7],
  //     }),
  //     stroke: new Stroke({
  //       color: "#1778dc",
  //     }),
  //   }),
  //   id,
  //   zIndex: 10005,
  // });
  // openMap.addLayer(vetorLayer);
  // fitVectorLayer(vetorLayer, openMap);
}
/* 
根据矢量图层定位（通过url的方式加载的图层）
layer：图层
openMap：地图对象
*/
export function fitVectorLayer(layer, openMap) {
  let ls = layer.getSource().on("change", function () {
    if (layer.getSource().getState() === "ready") {
      // 获取要素四至
      let extent = layer.getSource().getExtent();
      //定位范围
      openMap.getView().fit(extent, {
        duration: 1000, //动画的持续时间,
      });
      // 注销监听
      // layer.getSource().un(ls);
    }
  });
}
// 根据图层id删除图层
export function removeLayerById(id, openMap) {
  let allLayers = openMap.getLayers().array_;
  allLayers.forEach((item) => {
    if (item.values_.id == id) {
      openMap.removeLayer(item);
    }
  });
}

// 通过id判断图层是否已加载
export function layerIsExistById(id, openMap) {
  let allLayers = openMap.getLayers().array_;
  let flag = false;
  allLayers.forEach((item) => {
    if (item.values_.id == id) {
      flag = true;
    }
  });
  return flag;
}

// 通过id修改图层层级
export function modifylayerZindexById(id, openMap, zIndex) {
  let allLayers = openMap.getLayers().array_;
  allLayers.forEach((layer) => {
    if (layer.values_.id == id) {
      layer.setZIndex(zIndex);
    }
  });
}
// 通过id修改图层颜色
export function modifylayerColorById(id, openMap, color, borderWidth) {
  let allLayers = openMap.getLayers().array_;
  allLayers.forEach((layer) => {
    if (layer.values_.id == id) {
      layer.setStyle(
        new Style({
          //填充色
          fill: new Fill({
            // color: getColorStr("30"),
            color: "#B8B2B24D",
          }),
          //边线颜色
          stroke: new Stroke({
            color,
            width: borderWidth,
          }),
          //形状
          image: new Circle({
            radius: 7,
            fill: new Fill({
              color,
            }),
          }),
        })
      );
    }
  });
}

// 绘制点带文字
export function addPointArr(openMap, pointArr, id, textArr, zIndex) {
  let layerArr = [];
  pointArr.forEach((item, index) => {
    let pointLayer = new VectorLayer({
      source: new VectorSource({
        features: [],
      }),
      id,
      zIndex: zIndex,
    });
    let feature = new Feature({
      geometry: new Point(item),
    });
    let style = new Style({
      //填充色
      fill: new Fill({
        color: "#FF0000",
      }),
      //形状
      image: new Circle({
        radius: 7,
        fill: new Fill({
          color: textArr && textArr.length > 0 ? "#00FF40" : "#FF0000",
        }),
      }),
      text:
        textArr && textArr.length > 0
          ? new Text({
              font: "normal 15px 黑体",
              // // 对其方式
              textAlign: "center",
              // 基准线
              textBaseline: "middle",
              offsetY: -35,
              offsetX: 0,
              backgroundFill: new Stroke({
                color: "#2196F3",
              }),
              // 文本填充样式
              fill: new Fill({
                color: "rgba(236,218,20,1)",
              }),
              padding: [5, 5, 5, 5],
              text: textArr[index],
            })
          : null,
    });
    feature.setStyle(style);
    pointLayer.getSource().addFeature(feature);
    layerArr.push(pointLayer);
  });
  let layerGroup = new Group({
    layers: layerArr,
    id,
  });
  if (zIndex) {
    layerGroup.setZIndex(zIndex);
  }
  openMap.addLayer(layerGroup);
}

// 绘制中心点
export function addCenterPointArr(openMap, pointArr, id, textArr, zIndex) {
  let layerArr = [];
  pointArr.forEach((item, index) => {
    let pointLayer = new VectorLayer({
      source: new VectorSource({
        features: [],
      }),
      id,
      zIndex: zIndex,
    });
    let feature = new Feature({
      geometry: new Point(item),
    });
    let style = new Style({
      //填充色
      // fill: new Fill({
      //   color: "#FF0000",
      // }),
      //形状
      // image: new Circle({
      //   radius: 7,
      //   fill: new Fill({
      //     color: textArr&&textArr.length>0?"#00FF40":"#FF0000",
      //   }),
      // }),
      text:
        textArr && textArr.length > 0
          ? new Text({
              font: "bold 16px 黑体",
              // // 对其方式
              textAlign: "center",
              // 基准线
              textBaseline: "middle",
              offsetY: -35,
              offsetX: 0,
              backgroundFill: new Stroke({
                color: "#076476",
              }),
              // 文本填充样式
              fill: new Fill({
                color: "rgba(236,218,20,1)",
              }),
              padding: [5, 5, 5, 5],
              text: textArr[index] + "km²",
            })
          : null,
    });
    feature.setStyle(style);
    pointLayer.getSource().addFeature(feature);
    layerArr.push(pointLayer);
  });
  let layerGroup = new Group({
    layers: layerArr,
    id,
  });
  if (zIndex) {
    layerGroup.setZIndex(zIndex);
  }
  openMap.addLayer(layerGroup);
}

// 根据坐标添加定位点
export function addPointByLonLat(point, openMap) {
  let pointLayer = new VectorLayer({
    source: new VectorSource({
      features: [],
    }),
    id: "定位",
    zIndex: 1000000,
  });
  let feature = new Feature({
    geometry: new Point(point),
  });
  let style = new Style({
    image: new Icon({
      scale: 0.8,
      src: require("../assets/images/icon/定位place.png"),
      anchor: [0.48, 0.52],
    }),
  });
  feature.setStyle(style);
  pointLayer.getSource().addFeature(feature);
  openMap.addLayer(pointLayer);
  //定位坐标
  openMap.getView().animate({
    center: point, //动画结尾的视图中心
    zoom: 12, //这里可以指定到具体等级
    duration: 2000, //动画的持续时间
  });
}
// 恢复初始视角
export function backView(openMap) {
  openMap.getView().animate({
    center: [121.366, 34.91032], //动画结尾的视图中心
    zoom: 9, //这里可以指定到具体等级
    duration: 2000, //动画的持续时间
  });
}
// 添加高亮图层
export function addLightLayerArr(openMap, features) {
  // geojson方式
  let curLightLayer = new VectorLayer({
    zIndex: 1000000000,
    id: "高亮",
    source: new VectorSource({
      format: new GeoJSON(),
      // 使用上面的GeoJSON数据对象
      features: new GeoJSON().readFeatures(JSON.stringify(features)),
    }),
    style: new Style({
      fill: new Fill({
        color: "#ffffff60",
      }),
      //边线颜色
      stroke: new Stroke({
        color: "#03be86",
        width: 2,
      }),
    }),
  });

  // wkt对象方式
  // let featureArr = features.map((feature) => {
  //   let polygon = new Feature({
  //     id: feature.fid,
  //     geometry: new MultiPolygon(feature.geometry.coordinates),
  //   });
  //   polygon.setStyle(
  //     new Style({
  //       fill: new Fill({
  //         color: "#ffffff60",
  //       }),
  //       //边线颜色
  //       stroke: new Stroke({
  //         color: "#03be86",
  //         width: 2,
  //       }),
  //     })
  //   );
  //   return polygon;
  // });
  // let lightLayerList = new VectorLayer({
  //   zIndex: 1000000000,
  //   source: new VectorSource({
  //     features:featureArr,
  //     id: "高亮",
  //   }),
  // });
  openMap.addLayer(curLightLayer);
  return curLightLayer;
}

// 绘制图斑编号以及企业名称
export function addTextArr(openMap, featureArr, id, zIndex) {
  let layerArr = [];
  featureArr.forEach((item, index) => {
    let pointLayer = new VectorLayer({
      source: new VectorSource({
        features: [],
      }),
      zIndex: zIndex,
    });
    let feature = new Feature({
      geometry: new Point([item.properties.经度, item.properties.纬度]),
    });
    let style = new Style({
      //填充色
      fill: new Fill({
        color: "#FF0000",
      }),
      //形状
      image: new Circle({
        radius: 7,
        fill: new Fill({
          color: featureArr && featureArr.length > 0 ? "#00FF40" : "#FF0000",
        }),
      }),
      text:
        featureArr && featureArr.length > 0
          ? new Text({
              font: "normal 15px 黑体",
              // // 对其方式
              textAlign: "right",
              // 基准线
              textBaseline: "middle",
              offsetY: -20,
              offsetX: -20,
              backgroundFill: new Stroke({
                color: "#2196F3",
              }),
              // 文本填充样式
              fill: new Fill({
                color: "rgba(236,218,20,1)",
              }),
              padding: [5, 5, 5, 5],
              text:
                "(" + item.properties.图斑编号 + ")" + item.properties.养殖企业,
            })
          : null,
    });
    feature.setStyle(style);
    pointLayer.getSource().addFeature(feature);
    layerArr.push(pointLayer);
  });
  let layerGroup = new Group({
    layers: layerArr,
    id,
  });
  if (zIndex) {
    layerGroup.setZIndex(zIndex);
  }
  openMap.addLayer(layerGroup);
}

//飞行函数
export function flyTo(map, lon, lat, zoom, duration) {
  let transformCenter = transform([lon, lat], "EPSG:4326", "EPSG:3857");
  // 飞到指定位置
  map.getView().animate({
    zoom: zoom,
    center: transformCenter,
    duration: duration,
  });
}

//地图点击事件
export function WMSClick(openMap, layer, callback) {
  const wmsClickEvent = openMap.on("singleclick", function (evt) {
    const viewResolution = openMap.getView().getResolution();
    const url = layer
      .getSource()
      .getFeatureInfoUrl(evt.coordinate, viewResolution, "EPSG:3857", {
        INFO_FORMAT: "application/json",
      });
    if (url) {
      fetch(url)
        .then((response) => response.json())
        .then((data) => {
          console.log(data.features[0].geometry.type, "type");
          if (data.features?.length > 0) {
            callback({
              props: data.features[0].properties,
              wmsClickEvent,
            });
          } else {
            callback(null);
          }
        })
        .catch((error) => callback(null, error));
    }
  });
}

//地图点击事件
export function WMSClick_env(openMap) {
  console.log("WMSClick_env被调用了");

  try {
    // 获取popup的dom对象
    let container = document.getElementById("popup");
    let closer = document.getElementById("popup-closer");
    // 创建popup
    let popup = new Overlay({
      element: container,
      autoPan: true,
      positioning: "bottom-center",
      stopEvent: true,
      autoPanAnimation: {
        duration: 250,
      },
    });
    popupList.push(popup);
    map.addOverlay(popup);

    // 关闭popup
    closer.onclick = function () {
      popup.setPosition(undefined);
      closer.blur();
      return false;
    };
    // 关闭popup
    const envClickEvent = openMap.on("singleclick", function (evt) {
      popup.setPosition(evt.coordinate);
      container.style.visibility = "visible"; // 修改 CSS 属性
      const viewResolution = openMap.getView().getResolution();
      let resArr = openMap
        .getLayers()
        .getArray()
        .filter((layer) => layer.get("name") === "环境监测");
      //获取到数组最后一个
      let layer = resArr[resArr.length - 1];
      if (!layer) return;
      const url = layer
        .getSource()
        .getFeatureInfoUrl(evt.coordinate, viewResolution, "EPSG:3857", {
          INFO_FORMAT: "application/json",
        });
      if (url) {
        fetch(url)
          .then((response) => response.json())
          .then((data) => {
            if (data.features?.length > 0) {
              envPopperInfo.value = data.features[0].properties;
            } else {
              envPopperInfo.value = null;
            }
          })
          .catch((error) => {
            envPopperInfo.value = null;
            console.log(error);
          });
      }
    });
    clickEventList.push(envClickEvent);
  } catch (err) {
    console.log(err);
  }
}

//移除点击事件
export function removeClickEvent() {
  clickEventList.forEach((event) => {
    unByKey(event);
  });
}
//移除popup弹窗
export function removePopup() {
  popupList.forEach((popup) => {
    popup.setPosition(undefined);
  });
}

//添加轨迹线
/**
 * 在OpenLayers中添加一条虚线（模块化版本）
 * @param {Array} item1 - 起点坐标 [经度, 纬度]
 * @param {Array} item2 - 终点坐标 [经度, 纬度]
 * @param {VectorLayer} [vectorLayer] - 可选，已有的矢量图层（避免重复创建）
 */
export function addLine(map, item1, item2) {
  // 1. 初始化矢量图层（若未提供）
  const vectorSource = new VectorSource();
  let vectorLayer = new VectorLayer({
    source: vectorSource,
  });
  map.addLayer(vectorLayer);

  // 2. 创建线几何对象（坐标系转换）
  const lineString = new LineString([fromLonLat(item1), fromLonLat(item2)]);

  // 3. 创建线要素并设置虚线样式
  const lineFeature = new Feature({
    geometry: lineString,
  });

  const lineStyle = new Style({
    stroke: new Stroke({
      color: "red",
      width: 3,
      lineDash: [10, 5],
    }),
  });

  lineFeature.setStyle(lineStyle);

  // 4. 将要素添加到图层
  vectorLayer.getSource().addFeature(lineFeature);
  return { vectorLayer };
}

/**
 * 添加风场粒子图层
 * @param {*} map
 */
export async function addWindLayer(map, dataUrl) {
  const res = await getWindDataByJson(dataUrl);
  let windLayer = new WindLayer(res, {
    windOptions: {
      // velocityScale: 0.001, //粒子运动速度
      paths: 10000,
      colorScale: [
        "rgb(36,104, 180)",
        "rgb(60,157,194)",
        "rgb(128,205,193 )",
        "rgb(151,218,168 )",
        "rgb(198,231,181)",
        "rgb(238,247,217)",
        "rgb(255,238,159)",
        "rgb(252,217,125)",
        "rgb(255,182,100)",
        "rgb(252,150,75)",
        "rgb(250,112,52)",
        "rgb(245,64,32)",
        "rgb(237,45,28)",
        "rgb(220,24,32)",
        "rgb(180,0,35)",
      ],
      lineWidth: 2,
      generateParticleOption: false,
    },
    fieldOptions: {
      wrapX: false,
    },
  });
  map.addLayer(windLayer);
  return windLayer;
}
/**
 * 移除风场粒子图层
 * @param {*} map
 * @param {*} windLayer
 */
export function removeWindLayer(map, windLayer) {
  map.removeLayer(windLayer);
}

// 假设已初始化地图对象（map）和全局要素数组（allFeatures）
export function addBZPoint(map, item) {
  // 1. 初始化矢量图层（若未提供）
  const vectorSource = new VectorSource();
  let wrjVectorLayer = new VectorLayer({
    source: vectorSource,
  });
  map.addLayer(wrjVectorLayer);
  // 1. 坐标转换（WGS84经纬度 → Web Mercator投影）
  const coordinate = fromLonLat(item);
  // 2. 创建点要素（Feature）
  const pointFeature = new Feature({
    geometry: new Point(coordinate),
    type: "trackPoint", // 自定义属性
  });

  // 3. 设置图标样式（替代Cesium的billboard）
  pointFeature.setStyle(
    new Style({
      image: new Icon({
        src: wurenji, // 替换为实际图片路径
        scale: 0.2, // 缩放比例（等效Cesium的width/height）
        anchor: [0.5, 1], // 锚点位置（底部居中）
        // 等效Cesium的scaleByDistance（需手动实现缩放逻辑）
        opacity: 1, // 透明度控制
      }),
    })
  );

  // 4. 添加到矢量图层（假设已存在vectorLayer）
  wrjVectorLayer.getSource().addFeature(pointFeature);
  return { wrjVectorLayer };
}

/**
 * 优化后的轨迹绘制函数（支持动态箭头、双线效果、动画控制）
 * @param {ol.Map} map - OpenLayers地图实例
 * @param {Object} options - 配置参数
 * @param {Array} options.points - 轨迹点数组（需包含coord和time属性）
 * @param {string} [options.lineColor='#00FF00'] - 主轨迹线颜色
 * @param {string} [options.startColor='red'] - 起点颜色
 * @param {string} [options.endColor='yellow'] - 终点颜色
 */
export function showTimedTrajectory(map, options) {
  const {
    points,
    lineColor = "#00FF00",
    startColor = "green",
    endColor = "red",
  } = options;

  if (!points || points.length === 0) {
    console.error("轨迹点数据为空");
    return;
  }

  // 1. 初始化图层和源
  const vectorSource = new VectorSource();
  const vectorLayer = new VectorLayer({
    source: vectorSource,
    renderMode: "vector", // 使用矢量渲染优化性能[6](@ref)
  });
  map.addLayer(vectorLayer);

  // 2. 创建双线效果（底层阴影线 + 上层主色线）[8,9](@ref)
  const lineString = new LineString(points.map((p) => fromLonLat(p.coord)));
  const lineFeature = new Feature({ geometry: lineString });

  const lineStyles = [
    // 底层阴影线（加粗）
    new Style({
      stroke: new Stroke({
        color: "rgba(0,0,0,0.5)",
        width: 6,
      }),
    }),
    // 上层主色线
    new Style({
      stroke: new Stroke({
        color: lineColor,
        width: 4,
      }),
    }),
  ];
  // lineFeature.setStyle(lineStyles);
  // 在原有代码中替换 lineFeature.setStyle(lineStyles) 为以下内容：
  lineFeature.setStyle(function (feature, resolution) {
    const styles = [...lineStyles]; // 保留原有线样式
    const geometry = feature.getGeometry();

    geometry.forEachSegment((start, end) => {
      const midPoint = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2];
      const dx = end[0] - start[0];
      const dy = end[1] - start[1];
      const rotation = Math.atan2(dy, dx);

      styles.push(
        new Style({
          geometry: new Point(midPoint),
          image: new Icon({
            src: arrowImg,
            anchor: [0.5, 0.5],
            rotateWithView: true,
            rotation: -rotation - Math.PI / 2,
            scale: 0.2,
          }),
        })
      );
    });

    return styles;
  });
  vectorSource.addFeature(lineFeature);

  // 3. 添加标记点（含时间标签）
  points.forEach((point, index) => {
    const isStart = index === 0;
    const isEnd = index === points.length - 1;
    const pointFeature = new Feature({
      geometry: new Point(fromLonLat(point.coord)),
      time: point.time,
      label: isStart ? "起点" : isEnd ? "终点" : null,
    });
    // 标记点样式
    const styles = [
      new Style({
        image: new Circle({
          radius: isStart || isEnd ? 7 : 5,
          fill: new Fill({
            color: isStart
              ? startColor
              : isEnd
              ? endColor
              : "rgba(255, 255, 255, 0.8)",
          }),
          stroke: new Stroke({
            color: "#000",
            width: 2,
          }),
        }),
      }),
    ];
    // 时间标签
    if (point.time) {
      styles.push(
        new Style({
          text: new Text({
            text: point.time,
            offsetY: -25,
            offsetX: -70,
            fill: new Fill({ color: "#FFF" }),
            stroke: new Stroke({ color: "#000", width: 2 }),
            scale: 1,
            font: "bold 14px Arial",
          }),
        })
      );
    }
    // 特殊标记文本
    styles.push(
      new Style({
        text: new Text({
          text: isStart ? "起点" : isEnd ? "终点" : null,
          offsetY: 20,
          offsetX: 30,
          fill: new Fill({ color: "#fff" }),
          stroke: new Stroke({ color: "#000", width: 2 }),
          scale: 1.2,
          font: "bold 14px Arial",
        }),
      })
    );
    pointFeature.setStyle(styles);
    vectorSource.addFeature(pointFeature);
  });
  map.getView().fit(vectorSource.getExtent(), {
    padding: [50, 50, 50, 50],
    duration: 1000,
  });

  // 返回控制接口
  return {
    vectorLayer,
    vectorSource,
  };
}

/**
 * 支持动画的轨迹绘制函数
 * @param {ol.Map} map - OpenLayers地图实例
 * @param {Object} options - 配置参数
 * @param {Array} options.points - 轨迹点数组（需包含coord和time属性）
 * @param {string} [options.lineColor='#00FF00'] - 主轨迹线颜色
 * @param {string} [options.startColor='red'] - 起点颜色
 * @param {string} [options.endColor='yellow'] - 终点颜色
 * @param {number} [options.animationSpeed=100] - 动画速度（毫秒/点）
 */
export function showAnimatedTrajectory(map, options) {
  const {
    points,
    lineColor = "#00FF00",
    startColor = "green",
    endColor = "red",
    animationSpeed = 1000,
  } = options;

  if (!points || points.length === 0) {
    console.error("轨迹点数据为空");
    return;
  }

  // 1. 初始化图层和源
  const vectorSource = new VectorSource();
  const vectorLayer = new VectorLayer({
    source: vectorSource,
    renderMode: "vector",
    updateWhileAnimating: true, // 允许动画期间更新[1](@ref)
  });
  map.addLayer(vectorLayer);

  // 2. 创建双线效果
  const lineString = new LineString(points.map((p) => fromLonLat(p.coord)));
  const lineFeature = new Feature({ geometry: lineString });

  const lineStyles = [
    // 底层阴影线
    new Style({
      stroke: new Stroke({
        color: "rgba(0,0,0,0.5)",
        width: 6,
      }),
    }),
    // 上层主色线
    new Style({
      stroke: new Stroke({
        color: lineColor,
        width: 4,
      }),
    }),
  ];

  // 3. 动态箭头样式（沿轨迹分布）
  lineFeature.setStyle(function (feature) {
    const styles = [...lineStyles];
    const geometry = feature.getGeometry();

    geometry.forEachSegment((start, end) => {
      const midPoint = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2];
      const dx = end[0] - start[0];
      const dy = end[1] - start[1];
      const rotation = Math.atan2(dy, dx);

      styles.push(
        new Style({
          geometry: new Point(midPoint),
          image: new Icon({
            src: arrowImg,
            anchor: [0.5, 0.5],
            rotateWithView: true,
            rotation: -rotation - Math.PI / 2,
            scale: 0.2,
          }),
        })
      );
    });
    return styles;
  });
  vectorSource.addFeature(lineFeature);

  // 4. 创建所有轨迹点（初始隐藏）
  const pointFeatures = points.map((point, index) => {
    const feature = new Feature({
      geometry: new Point(fromLonLat(point.coord)),
      time: point.time,
      isActive: false,
      label: index === 0 ? "起点" : index === points.length - 1 ? "终点" : null,
    });
    feature.setStyle(getPointStyle(index, false));
    vectorSource.addFeature(feature);
    return feature;
  });

  // 5. 动画控制逻辑
  let currentIndex = 0;
  let animationId = null;
  let lastRenderTime = 0;

  // 动画帧函数
  const animate = (timestamp) => {
    if (!lastRenderTime) lastRenderTime = timestamp;
    const elapsed = timestamp - lastRenderTime;

    if (elapsed >= animationSpeed) {
      // 更新当前点和下一个点的样式
      pointFeatures[currentIndex]?.setStyle(getPointStyle(currentIndex, false));
      currentIndex++;
      // // 移动视图中心（平滑跟随）
      const coord = fromLonLat(points[currentIndex].coord);
      map.getView().animate({
        center: coord,
        duration: 1500,
      });
      if (currentIndex >= points.length) {
        cancelAnimationFrame(animationId);
        return;
      }
      pointFeatures[currentIndex]?.setStyle(getPointStyle(currentIndex, true));
      lastRenderTime = timestamp;
    }
    animationId = requestAnimationFrame(animate);
  };

  // 点样式生成函数
  function getPointStyle(index, isActive) {
    const isStart = index === 0;
    const isEnd = index === points.length - 1;
    const point = points[index];

    const styles = [
      new Style({
        image: new Circle({
          radius: isActive ? 10 : isStart || isEnd ? 7 : 5,
          fill: new Fill({
            color: isActive
              ? "#0d74db"
              : isStart
              ? startColor
              : isEnd
              ? endColor
              : "rgba(255,255,255,0.8)",
          }),
          stroke: new Stroke({
            color: isActive ? "#FFF" : "#000",
            width: isActive ? 3 : 2,
          }),
        }),
      }),
    ];

    // 时间标签
    if (point.time) {
      styles.push(
        new Style({
          text: new Text({
            text: point.time,
            offsetY: -25,
            offsetX: -70,
            fill: new Fill({ color: "#FFF" }),
            stroke: new Stroke({ color: "#000", width: 2 }),
            font: "bold 14px Arial",
          }),
        })
      );
    }

    // 起点/终点标签
    if (isStart || isEnd) {
      styles.push(
        new Style({
          text: new Text({
            text: isStart ? "起点" : "终点",
            offsetY: 20,
            fill: new Fill({ color: "#FFF" }),
            stroke: new Stroke({ color: "#000", width: 2 }),
            font: "bold 14px Arial",
          }),
        })
      );
    }

    return styles;
  }

  // 初始适配视图
  map.getView().fit(vectorSource.getExtent(), {
    padding: [50, 50, 50, 50],
    duration: 1000,
  });

  // 返回控制接口
  return {
    vectorLayer,
    vectorSource,
    startAnimation: () => {
      if (animationId) cancelAnimationFrame(animationId);
      currentIndex = 0;
      animationId = requestAnimationFrame(animate);
    },
    stopAnimation: () => {
      cancelAnimationFrame(animationId);
      animationId = null;
    },
    resetAnimation: () => {
      pointFeatures.forEach((f, i) => f.setStyle(getPointStyle(i, false)));
      currentIndex = 0;
    },
  };
}

//指定位置添加点并设置图标
export function addPoint(map, coord, color = "#FF0000") {
  const vectorLayer = new VectorLayer({
    source: new VectorSource({
      features: new Feature({
        geometry: new Point(coord),
        style: new Style({
          image: new Icon({
            anchor: [0.5, 1],
            src: ship,
          }),
        }),
      }),
    }),
  });
  map.addLayer(vectorLayer);
}
